from django.shortcuts import render,HttpResponse,redirect
from rest_framework.views import APIView
from rest_framework.response import Response
from configuration.sms_code import send_message
import string
import random
from captcha.image import ImageCaptcha
import redis
import jwt
from customer.models import *
import time
from django.conf import settings
from configuration.jwt_decode import check_login
from configuration.pay import AlipayTool
from django.db.models import Q
# Create your views here.
# 顾客视图


# 图片验证码的视图
class ImageCodeAPIView(APIView):
    def get(self, request, uuid):
        # 生成一个4位数随机码
        # string.ascii_letters：a-zA-Z所有字母
        # string.digits：数字0-9
        # random.sample：随机采样(返回列表类型)
        code = "".join(random.sample(string.ascii_letters + string.digits, 4))
        # 实例化一个图片验证码对象
        # 用captcha.image下的 ImageCaptcha 生成字符验证码图片
        img = ImageCaptcha()
        # 把这个验证码转换成图片形式的
        image_code = img.generate(code)  # 字节io对象
        # 验证码存入redis
        redis_conn = redis.Redis(host="localhost", port=6379,password='123321')
        redis_conn.set(uuid, code, ex=5 * 60)

        # 返回响应
        return HttpResponse(image_code, content_type="image/png")


# 获取验证码
class SmsView(APIView):
    def get(self,request,mobile):
        uuid = request.query_params.get('uuid')
        code = request.query_params.get('code')
        if not all([uuid,code]):
            return Response({
                'code':400,
                'msg':'获取数据为空'
            })
        # 我去做个核酸，我在，
        print('>>>>>>>>>>',uuid,code)
        # 取出redis中uuid的值
        redis_conn = redis.Redis(host="localhost", port=6379,password='123321')
        code_r = redis_conn.get(uuid)
        print('>>>>>>>>>>>>>>',code_r)
        if not code_r:
            return Response({
                'code':400,
                'msg':'校验码已过期'
            })
        # 验证码还未过期，解码与前端对比
        if code_r.decode().lower() != code.lower():
            return Response({
                "code": 400,
                "msg": "校验码错误"
            })

        send_message(mobile)
        return Response({
            'code':200,
            'msg':'发送成功'
        })


# 手机验证码登入或注册
class UserView(APIView):
    def post(self,request):
        mobile = request.data.get('mobile')
        sms = request.data.get('sms')
        if not all([mobile,sms]):
            return Response({
                'code':400,
                'msg':'获取数据为空'
            })

        # 取出redis中uuid的值
        redis_conn = redis.Redis(host="localhost", port=6379,password='123321')
        key = 'sms_%s' % mobile
        code_r = redis_conn.get(key)
        if not code_r:
            return Response({
                'code': 400,
                'msg': '验证码已过期'
            })
        # 验证码还未过期，解码与前端对比
        if code_r.decode().lower() != sms.lower():
            return Response({
                "code": 400,
                "msg": "验证码错误"
            })

        # 判断此手机号是否注册
        user = CusUserModel.objects.filter(mobile=mobile)
        if not user:
            # 没有注册，进行注册
            CusUserModel.objects.create(
                mobile=mobile,
            )
        try:
            user = CusUserModel.objects.get(mobile=mobile)
        except Exception as e:
            return Response({
                'code':400,
                'msg':'没有此信息'
            })

        token = jwt.encode({
            'uid':user.id,
            'username':user.c_name,
            'exp':time.time() + 720000
        },key=settings.SECRET_KEY,algorithm='HS256')

        return Response({
            'code':200,
            'msg':'登入成功',
            'token':token
        })
    # eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOjEsInVzZXJuYW1lIjoiIiwiZXhwIjoxNjcwNTgyOTIzLjE0MTEyMjZ9.A47mXixaowvw1X5TxH2FvgFw4uqqRzxx9PsbKZpuPEs


# 客户收藏商品 添加收藏 获取收藏 取消收藏
class CollectView(APIView):
    # 获取收藏
    @check_login
    def get(self,request):
        u_id = request.uid
        cus = CollectModel.objects.filter(user_id=u_id,delete=False)
        cus_list = []
        for i in cus:
            cus_list.append({
                'id':i.good.id,
                'g_name':i.good.g_name,
                'img':i.good.img,
                'price':i.good.price,
                'inventory':i.good.inventory,
                'burdening':i.good.burdening,
            })

        return Response({
            'code':200,
            'msg':'获取成功',
            'data':cus_list
        })

    @check_login
    def post(self,request):
        # 添加收藏 获取前端数据
        good_id = request.data.get('gid')

        if not good_id:
            return Response({
                'code':400,
                'msg':'获取数据为空'
            })
        u_id = request.uid

        cus = CollectModel.objects.filter(good_id=good_id).first()
        if not cus:
            # 进行添加收藏
            CollectModel.objects.create(
                good_id=good_id,
                user_id=u_id,
            )
            return Response({
                'code': 200,
                'msg': '收藏成功'
            })

        if cus.delete == False:

            cus.delete = True
            cus.save()
            return Response({
                'code':201,
                'msg':'取消收藏成功'
            })
        else:
            cus.delete = False
            cus.save()
            return Response({
                'code':202,
                'msg':'收藏成功'
            })

# 获取单个收藏信息
class CollectInfoView(APIView):
    @check_login
    def get(self,request):
        uid = request.uid
        gid = request.query_params.get('gid')
        print('>>>>>>>>>>>',uid,gid)
        try:
            collect = CollectModel.objects.get(user_id=uid,good_id=gid)
        except Exception as e:
            print('>>>>>>>>',e)
            return Response({
                'code':400,
                'msg':'您还没有收藏',
                'data': {
                    'delete': 1
                }
            })

        return Response({
            'code':200,
            'msg':'获取成功',
            'data':{
                'delete':collect.delete
            }
        })
# 获取用户收货地址
class UserAddressView(APIView):
    @check_login
    def get(self,request):
        user = request.uid
        user_addres = AddressModel.objects.filter(user_id=user,delete=False)
        temp=[]
        for i in user_addres:
            temp_dict={
                "aid":i.id,
                "name":i.name,
                "mobile":i.mobile,
                "detail":i.detail,
                "default":i.default,
            }
            temp.append(temp_dict)
        return Response({
            "code":200,
            "msg":"获取登录用户收货地址成功",
            "data":temp,
        })

    @check_login
    def post(self, request):
        user_id = request.uid
        name = request.data.get("name")
        mobile = request.data.get("mobile")
        detail = request.data.get("detail")
        default = request.data.get('defaults')

        print('>>>>>>>>>',name,mobile,detail,default)

        if not all([name,mobile,detail]):
            return Response({
                'code':400,
                'msg':'获取数据失败'
            })

        try:
            addr = AddressModel.objects.filter(user_id=user_id,default=True).first()
            if not addr:
                AddressModel.objects.create(user_id=user_id, name=name, mobile=mobile, detail=detail,default=default)
                return Response({
                    'code':201,
                    'msg':'地址添加成功'
                })

            if int(default) == int(1):
                AddressModel.objects.create(user_id=user_id, name=name, mobile=mobile, detail=detail, default=default)
                addr.default = False
                addr.save()
                return Response({
                    'code': 202,
                    'msg': '地址添加成功'
                })

            AddressModel.objects.create(user_id=user_id, name=name, mobile=mobile, detail=detail, default=default)

        except Exception as e:
            print(e, "用户添加收货地址报错")
            return Response({
                'code':400,
                'msg':'地址添加错误'
            })
        return Response({
            "code": 200,
            "msg": "添加用户收货地址成功",
        })


    @check_login
    def put(self, request):
        user_id = request.uid

        id = request.data.get("aid")
        name = request.data.get("name")
        mobile = request.data.get("mobile")
        detail = request.data.get("detail")
        default = request.data.get('defaults')

        print("??????>>>>>>>",id,name,mobile,detail,default)

        try:
            addr = AddressModel.objects.filter(Q(user_id=user_id) & Q(default=True)).first()
            print('>>>>>>>>>',addr)
            if not addr:
                AddressModel.objects.filter(id=id).update(name=name, mobile=mobile, detail=detail, default=default)
                return Response({
                    'code': 201,
                    'msg': '地址修改成功'
                })

            if int(default) == int(1):
                AddressModel.objects.filter(id=id).update(name=name, mobile=mobile, detail=detail, default=default)
                if addr.id != int(id):
                    addr.default = False
                    addr.save()
                return Response({
                    'code': 202,
                    'msg': '地址修改成功'
                })

            AddressModel.objects.filter(id=id).update(name=name, mobile=mobile, detail=detail, default=default)
        except Exception as e:
            print(e, "用户修改收货地址报错")
            return Response({
                'code':400,
                'msg':'修改失败'
            })
        return Response({
            "code": 200,
            "msg": "修改用户收货地址成功",
        })

    def delete(self,request):
        id = request.query_params.get('id')
        print('>>>>>>>',id)
        try:
            addr = AddressModel.objects.get(id=id)
            addr.delete = True
            addr.save()
            return Response({
                'code':200,
                'msg':'删除成功',
            })
        except Exception as e:
            print('><><><><',e)
            return Response({
                'code':400,
                'msg':'删除失败'
            })


# 获取单个地址
class UserAddressInfoView(APIView):
    @check_login
    def get(self,request,id):
        try:
            addr = AddressModel.objects.get(id=id)
        except Exception as e:
            return Response({
                'code':400,
                'msg':'获取失败'
            })
        return Response({
            'code':200,
            'msg':'获取成功',
            'data':{
                "aid": addr.id,
                "name": addr.name,
                "mobile": addr.mobile,
                "detail": addr.detail,
                "defaults": addr.default,
            }
        })


# 获取默认地址
class DefaultAddressInfoView(APIView):
    def get(self,request):
        try:
            addr = AddressModel.objects.get(default=True)
        except Exception as e:
            print('>>>>>>>',e)
            return Response({
                'code':400,
                'msg':'获取失败'
            })

        return Response({
            'code':200,
            'msg':"获取成功",
            'data':{
                "aid": addr.id,
                "name": addr.name,
                "mobile": addr.mobile,
                "detail": addr.detail,
                "defaults": addr.default,
            }
        })

# 获取用户优惠券
class ShowuserCoupon(APIView):
    @check_login
    def get(self,request):
        id = request.uid
        user_coup = CouponModel.objects.filter(uid=id)
        temp = []

        for i in user_coup:
            temp_dict = {
                "id":i.uid,
                "name":i.name,
                "price":i.price,
                "type":i.address,
                "start_time":i.start_time,
                "end_time": i.end_time,
                "time": i.time,
            }
            temp.append(temp_dict)
        return Response({
            "code":200,
            "msg":"获取登录用户优惠卷成功",
            "data":temp,
        })


from configuration.qiniu_token import qiniu_token


# 获取七牛云token
class QNYtoken(APIView):
    def get(self,request):
        token = qiniu_token()

        return Response({
            "code":200,
            "token":token
        })


# 获取用户信息
class Show_userInfo(APIView):
    @check_login
    def get(self,request):
        u_id = request.uid
        try:
            users = CusUserModel.objects.get(id=u_id)
        except Exception as e:
            return Response({
                'code':400,
                'msg':'没有此用户信息'
            })

        return Response({
            "code":200,
            "msg":"获取登录用户信息成功",
            "data":{
                "id": users.id,
                "nickname": users.nickname,
                'c_name':users.c_name,
                "mobile": users.mobile,
                "portrait": users.portrait,
                "member": users.member,
                "establish_time": users.establish_time,
                "gender": users.gender
            },
        })

    @check_login
    def put(self,request):
        username = request.data.get("c_name")
        img = request.data.get("portrait")
        id = request.uid

        try:
            CusUserModel.objects.filter(id=id).update(c_name=username,portrait=img)
        except Exception as e:
            print(e)
        return Response({
            "code":200,
            "msg":"修改用户信息成功"
        })


# 获取VIP
class VipListView(APIView):
    def get(self,request):
        vip_list = VipListModel.objects.all()

        vip_all = []
        for item in vip_list:
            vip_all.append({
                "id": item.id,
                "name": item.name,
                "price": str(item.price),
                "time_text": item.time_text,
                "time": item.time,
                # "day_price": float(item.price) / float((item.time / 86400))
            })

        return Response({
            "code":200,
            "msg":"获取所以vip类型成功",
            "data":vip_all
        })


from datetime import datetime


# 获取所有订单
class Add_OrderView(APIView):
    @check_login
    def get(self,request):
        user_id = request.uid
        orders = PayOrderModel.objects.filter(uid_id=user_id)

        temp = []
        for i in orders:

            order_temp = {
                "id":i.id,
                "order_num":i.order_num,
                "uid": i.uid_id,
                "bid": i.bid_id,
                "fid":{
                    'f_name':i.fid.g_name,
                    'burdening':i.fid.burdening,
                    'price': i.fid.price,
                    'f_img': i.fid.img,
                },
                "price": i.fid.price,
                "amount": i.amount,
                "status":i.status,
                'status_name':'已支付' if i.status else '待支付'
            }
            temp.append(order_temp)
        return Response({
            "code":200,
            "msg":"获取用户所有订单成功",
            "data": temp,
        })

    # 生成订单
    @check_login
    def post(self,request):
        user_id = request.uid
        # 订单商家id
        bid = request.data.get("bid")
        # 菜品id
        fid = request.data.get("fid")
        # 价钱
        money = request.data.get("money")

        # 生成订单号
        order_num = "T" + datetime.strftime(datetime.now(), "%Y%m%d%H%M%S") + str(
            random.randint(100000, 999999)) + str(
            random.randint(100000, 999999))

        try:
            PayOrderModel.objects.create(uid_id=user_id,order_num=order_num,bid_id=bid,fid_id=fid,amount=money,status="1")
        except Exception as e:
            print(e,"生成未支付用户订单保存")
            return Response({
                "code": 305,
                "msg": "用户添加订单失败"
            })

        # 3.调用SDK下面的方法
        url = AlipayTool().create_order(
            title="支付订单 - %s" % user_id,
            price=money,
            order_num=order_num
        )

        return Response({
            "url": url,
        })

    @check_login
    def delete(self,request):
        user_id = request.uid
        id = request.query_params.get("id")
        try:
            ss = PayOrderModel.objects.filter(uid=user_id).filter(id=id).first()
            ss.delete()
        except Exception as e:
            print(e, "删除用户订单报错")
            return Response({
                "code": 305,
                "msg": "用户删除订单失败"
            })

        return Response({
            "code": 200,
            "msg": "用户删除订单成功"
        })

# 回调，
class PayNotifyView(APIView):
    def get(self,request):
        """接收同步地址回调"""
        agrs = request.get.dict()
        sign = agrs.pop("sign")

        # 因为是get请求，且地址啥的都是公开的。为了保证安全性，需要对回调数据进行校验
        alipay = AlipayTool().alipay

        rs = alipay.verify(agrs, sign)
        if not rs:
            return Response({
                "code":301,
                "msg":"鉴权失败"
            })

        # 把订单的状态改为已支
        order = PayOrderModel.objects.filter(order_num=agrs["out_trade_no"]).first()

        if order.status != 0:
            return Response({
                "code":302,
                "msg":"订单状态不允许"
            })

        order.status = 1
        order.save()

        return redirect("http://127.0.0.1:8080/home")


# 获取支付成功记录
class OrderRecordView(APIView):
    @check_login
    def get(self,request):
        user_id = request.uid

        order_list = PayOrderModel.objects.filter(status=1).filter(uid=user_id).all()

        order_all = []
        for item in order_list:
            order_all.append({
                "order_num": item.order_num,
                "uid": item.uid.username,
                "fid": item.fid.name,
                "buss_name": item.bid.title ,
                "amount": str(item.amount),
                "status": item.status,
            })

        return Response({
            "code":200,
            "msg":"获取支付记录成功",
            "data":order_all
        })


# 评论商家
class CommentView(APIView):
    def get(self,request):
        # 获取评论
        good_id = request.query_params.get('gid')
        comment = CommentModel.objects.filter(good_id_id=good_id)
        comment_list = []
        for i in comment:
            comment_list.append({
                'coid':i.id,
                'user':{
                    'username':i.user_id.c_name,
                    'portrait':i.user_id.portrait,
                },
                'context':i.context,
            })

        return Response({
            'code':200,
            'msg':'评论获取成功',
            'data':comment_list,
        })

    @check_login
    def post(self,request):
        # 获取前端数据
        user_id = request.uid
        good_id = request.data.get('gid')
        context = request.data.get('context')
        parent_id = request.data.get('parent_id')
        root_id = request.data.get('root_id')

        if not all([good_id,context]):
            return Response({
                'code':200,
                'msg':'获取数据为空'
            })
        CommentModel.objects.create(user_id_id=user_id,good_id_id=good_id,context=context,parent_id=parent_id,root_id=root_id)

        return Response({
            'code':200,
            'msg':'评论成功'
        })

    @check_login
    def delete(self,request):
        user_id = request.uid
        comm_id = request.query_params.get('commid')

        try:
            comment = CommentModel.objects.get(id=comm_id)

            if comment.user_id_id != user_id:
                return Response({
                    'code':400,
                    'msg':'不是您的评论不可删除'
                })

            comment.delete()
            comment.save()

        except Exception as e:
            return Response({
                'code':200,
                'msg':'没有此评论'
            })

# 通过手机号获取头像
class MobileView(APIView):
    def get(self,request,mobile):
        try:
            cus = CusUserModel.objects.get(mobile=mobile)
        except Exception as e:
            print('>>>>>>>>',e)
            return Response({
                'code':400,
                'msg':'获取失败',
            })

        return Response({
            'code':200,
            'msg':'获取成功',
            'data':{
                'img':cus.portrait,
            }
        })


